/*
Download:
http://prdownloads.sourceforge.net/cpearls/simple_but_common.tar.gz?download

  Sample usage:

    $ .getline
       Enter some text here
       and more text
       ^D

*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <regex.h>
#include <string.h>

#define MSGBUFSIZE 1024

char *myerror;
char tbuf[MSGBUFSIZE];
int ignore_case = 0;
int extended = 0;
int errors = 0;

regex_t pattern;


char * parse(const char *s,int _start,char *tbuf)
{
  int start=0;
  const char *porg;
  const char *sp;
  const char *ep;
  char *ptbuf;

  porg=s;

  *tbuf='\0';

  while(*s != '\0') {
    if(*s == ' ')
      start++;
    if(start == (_start) ) {
      while(*s == ' '){ s++; }
      sp=s;
      start++;
    }

    if(start == (_start+2)) {
      ep=s;
      ptbuf=tbuf;
      while(sp != ep)
        { *tbuf++=*sp++; }
      *tbuf='\0';
      tbuf=ptbuf;
      //      fprintf(stderr,"->%s<-\n",tbuf);
      start++;
    }

    s++;
  }

  s=porg;
  return tbuf;
}



void compile_pattern(const char *pat)
{
	int flags = REG_NOSUB;
	int ret;
	char error[MSGBUFSIZE];

	// Ignore case
	flags |= REG_ICASE;
	// Extended
	flags |= REG_EXTENDED;
	ret = regcomp(&pattern, pat, flags);
	if (ret != 0) {
		(void) regerror(ret, &pattern, error, sizeof error);
		fprintf(stderr, "%s: pattern '%s': %s\n", myerror, pat,
			error);
		errors++;
	}
}

void process(const char *name, FILE * fp)
{
	char *buf = NULL;
	size_t size = 0;
	char error[MSGBUFSIZE];
	int ret;

	while (getline(&buf, &size, fp) != -1) {
		ret = regexec(&pattern, buf, 0, NULL, 0);
		if (ret != 0) {
			if (ret != REG_NOMATCH) {
				(void) regerror(ret, &pattern, error,
						sizeof error);
				fprintf(stderr, "%s: file %s: %s\n",
					myerror, name, error);
				free(buf);
				errors++;
				return;
			}
		} else {
		  printf("(%s)\n",parse(buf,0,tbuf));
		  printf("(%s)\n",parse(buf,1,tbuf));
		  printf("(%s)\n",parse(buf,2,tbuf));
		  printf("(%s)\n",parse(buf,12,tbuf));

		}
	}
	free(buf);
}



int main(int argc, char **argv)
{
	FILE *fp;
	if (argc != 3) {
		fprintf(stderr, "regex <reg expression> <file>\n\n");
		return -1;
	}

	compile_pattern(argv[1]);	/* compile the pattern */
	if (errors)		/* compile failed */
		return 1;

	if ((fp = fopen(argv[2], "r")) != NULL) {
		process(argv[2], fp);
		fclose(fp);
	}

}
